package com.sohu.peak.util;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * User: PengYouHui
 * Date: 2008-6-23
 * Time: 9:17:28
 */

public class ImageUtil {
	private static final Logger log = new Logger();
    public static boolean saveImageWithSizeCheck(String sourceUrl, String path) {
        ImageUtilThread imageUtilThread = new ImageUtilThread(sourceUrl, path);
        return imageUtilThread.saveAndConvert();
    }

    static class ImageUtilThread {
        private String sourceUrl;
        private String imagePath;
        private String imageName;

        ImageUtilThread(String sourceUrl, String imagePath) {
            this.sourceUrl = sourceUrl;
            this.imagePath = imagePath.substring(0, imagePath.lastIndexOf("/") + 1);
            this.imageName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
            this.imageName = this.imageName.substring(0, imageName.indexOf(".")) + "_1" + this.imageName.substring(imageName.indexOf("."));
        }

        public boolean saveAndConvert() {
            boolean result = true;
            try {
                sourceUrl = sourceUrl.trim();
                sourceUrl = sourceUrl.replaceAll(" ","%20");
                String command = "/usr/bin/wget --timeout=15  -O " + imageName + "  --referer=" + sourceUrl + " " + sourceUrl+"";
                excuteShell(command, imagePath);
                File imageFile = new File(imagePath + imageName);
                if (!imageFile.exists() || imageFile.length() == 0)
                    throw new Exception("currently can't catch the file:" + sourceUrl);
                BufferedImage sourceImg = null;
                int width = 0;
                try {
                    sourceImg = ImageIO.read(imageFile);
                    width = sourceImg.getWidth();
                } catch (Throwable e) {
                    //获取不到图片大小时不抛出异常
                }

                sourceImg = null;
                int convertWidth = 122;
                if (width < convertWidth && width > 0)
                    convertWidth = width;
                command = "/usr/local/bin/convert -strip -sample " + convertWidth + " -border 1 -bordercolor black " + imageName + "  " + imageName.replace("_1", "_m");

                excuteShell(command, imagePath);
                checkFileSize(imagePath, imageName.replace("_1", "_m"), convertWidth);

                convertWidth = 170;
                if (width < convertWidth && width > 0)
                    convertWidth = width;
                command = "/usr/local/bin/convert -strip -sample " + convertWidth + " -border 1 -bordercolor black " + imageName + "  " + imageName.replace("_1", "_b");
                excuteShell(command, imagePath);
                checkFileSize(imagePath, imageName.replace("_1", "_b"), convertWidth);
            } catch (Throwable e) {
                e.printStackTrace();
                result = false;
            }
            return result;
        }


        public void excuteShell(String command, String path) throws IOException, InterruptedException {
            Process proc = null;

            if (path != null) {
                java.io.File file = new java.io.File(path);
                Runtime runtime = Runtime.getRuntime();
                proc = runtime.exec(command, null, file);
                proc.waitFor();

            } else {
                Runtime runtime = Runtime.getRuntime();
                proc = runtime.exec(command);
                proc.waitFor();
                InputStream inputstream = proc.getInputStream();
                BufferedReader dataReader = new BufferedReader(new InputStreamReader(inputstream));
                String line = null;

                while ((line = dataReader.readLine()) != null) {
                    log.debug(line);
                }
                dataReader.close();
            }
            proc.destroy();
        }

        private void checkFileSize(String filePath, String fileName, int pixels) throws IOException, InterruptedException {
            File file = new File(filePath + fileName);
            if (file.exists()) {
                int quality = 100;
                //if(file.length()>12000){
                while (file.length() > 12000) {
                    quality = quality - 20;
                    if (quality < 10)
                        break;
                    //String command = "/usr/bin/convert -quality "+quality+" "+fileName+ " " +fileName;
                    String command = "/usr/local/bin/convert -strip -sample " + pixels + " -border 1 -bordercolor black -quality " + quality + " " + fileName.replace("_b", "_1").replace("_m", "_1") + " " + fileName;
                    excuteShell(command, filePath);
                    
                    file = new File(filePath + fileName);
                }
            }
        }
    }
    
    public static void main(String[] args) {
    	ImageUtil.saveImageWithSizeCheck("http://m3.biz.itc.cn/pic/t/94/79/Img307994_t.jpg", "/test.jpg");
    }
}
